//
//  AddKsViewController.swift
//  iKinds
//
//  Created by kinds on 2016/11/14.
//  Copyright © 2016年 Razeware LLC. All rights reserved.
//

import UIKit
import CoreData

//class AddKsViewController: UIViewController {
class AddKsViewController:CenterViewController{
	//是否以Push方式进入该VC,默认为是
	var enterByPush = true
	
	@IBOutlet weak var txtTitle: UITextField!
	@IBOutlet weak var ksTypeSeg: UISegmentedControl!
	
	@IBOutlet weak var txtRange: UITextField!
	
	@IBOutlet weak var txtClassify: UITextField!
	
	@IBOutlet weak var txtBody: UITextView!
	
	@IBOutlet weak var txtExceptions: UITextView!
	
	@IBOutlet weak var txtSignature: UITextField!
	
	@IBOutlet weak var rangeLabel: UILabel!
	
	@IBOutlet weak var segTimeUnit: UISegmentedControl!
	
	@IBAction func createKs(_ sender: UIButton) {
		
		//let childCtx = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
		//childCtx.parent = containerVC.managedObjectContext
		
		//if let entity = NSEntityDescription.entity(forEntityName: "KsMain", in: childCtx){
		//	let ks = KsMain(entity:entity,insertInto:childCtx)
		if let entity = NSEntityDescription.entity(forEntityName: "KsMain", in: containerVC.managedObjectContext){
			if let ks = NSManagedObject(entity: entity, insertInto: containerVC.managedObjectContext) as? KsMain{
            //if let ks = NSManagedObject(entity: entity, insertInto: nil) as? KsMain{
				//ks.dateBegin = start
				//ks.dateEnd = end
				
                start = nil
                end = nil
                
				if let rangeString = txtRange.text{
					if let rq = KsRangeQuery(string: rangeString){
						if let range = rq.match(){
							start = range.0
							end = range.1
							rangeLabel.text = "\(standardDateFor(date: range.0))-\(standardDateFor(date: range.1))"
						}
					}
				}
				
                ks.type = typeString
                ks.makeTypeLongTerm()
                typeString = ks.type ?? ""
                
				ks.dateBegin = start
				ks.dateEnd = end
                ks.id = 0
                
                switch segTimeUnit.titleForSegment(at: segTimeUnit.selectedSegmentIndex)!{
                    case "分钟":ks.ktrlTimeUnit = KsMain.timeUnit.perMinute.rawValue
                    case "小时":ks.ktrlTimeUnit = KsMain.timeUnit.perHour.rawValue
                    case "天":ks.ktrlTimeUnit = KsMain.timeUnit.perDay.rawValue
                default:// "月"
                    ks.ktrlTimeUnit = KsMain.timeUnit.perMonth.rawValue
                }
				//ks.ktrlTimeUnit = segTimeUnit.titleForSegment(at: segTimeUnit.selectedSegmentIndex)
				
                ks.calcScores()
                
                ks.classify = txtClassify.text
                ks.exception = txtExceptions.text
				ks.result = false
				ks.signature = txtSignature.text
				ks.text = txtBody.text
				ks.title = titleString
				
				containerVC.insertKsMain(ks: ks)
			}
		}
	}
    
    func hasKsType(_ type:KsMain.type)->Bool{
        return typeString.contains(type.rawValue.logo)
    }
	
	var start,end:Date?
	
	func msg(title:String,msg:String){
		let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
		alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
		present(alert, animated: true, completion: nil)
	}
	/*
	func standardDateFor(date:Date)->String{
		let f = DateFormatter()
		f.calendar = Calendar.current
		//f.timeZone = TimeZone(abbreviation: "GMT+8")
		f.timeZone = TimeZone.current
		f.dateFormat = "yyyy-MM-dd HH:mm:ss"
		return f.string(from: date)
	}*/
	
	func textFieldDidEndEditing(_ textField: UITextField) {
		if textField == txtRange , let text = textField.text {
			if let rq = KsRangeQuery(string: text){
				if let r = rq.match(){
					rangeLabel.text = "\(standardDateFor(date: r.0))-\(standardDateFor(date: r.1))"
					var segIndex = 0
					if let unit = rq.recommendTimeUnit(start: r.0, end: r.1){
						switch unit{
						case .perMinute:segIndex = 0
						case .perHour:segIndex = 1
						case .perDay:segIndex = 2
						case .perMonth:segIndex = 3
						}
						
						start = r.0
						end = r.1
                        
                        if let entity = NSEntityDescription.entity(forEntityName: "KsMain", in: containerVC.managedObjectContext){
                            //let fakeKs = KsMain()
                            if let fakeKs = NSManagedObject(entity: entity, insertInto: nil) as? KsMain{
                                fakeKs.dateBegin = start
                                fakeKs.dateEnd = end
                                fakeKs.type = typeString
                                fakeKs.makeTypeLongTerm()
                                typeString = fakeKs.type ?? ""
                            }
                        }
					}
					segTimeUnit.selectedSegmentIndex = segIndex
				}else{
					rangeLabel.text = "时间范围格式错误"
				}
			}else{
				rangeLabel.text =  "时间范围创建失败"
			}
		}
	}
	
	var typeString:String = ""{
		didSet{
			if var text = txtTitle.text{
				text = text.substring(from: text.characters.index(text.startIndex, offsetBy: oldValue.characters.count))
				txtTitle.text = "\(typeString)\(text)"
			}else{
				txtTitle.text = "\(typeString)"
			}
		}
	}
	
	var titleString:String? {
		if let text = txtTitle.text{
			if text.characters.count == 0{
				return nil
			}
			return text.substring(from: text.characters.index(text.startIndex, offsetBy: typeString.characters.count))
		}
		return nil
	}
	
	@IBAction func segTypeTapped(_ sender: UISegmentedControl) {
		var typeAry:[String] = []
	
		typeString.characters.forEach {c in
			typeAry.append(String(c))
		}
		
		let idx = sender.selectedSegmentIndex
		let type = sender.titleForSegment(at: idx)!
		if let i = typeAry.index(of: type){
			typeAry.remove(at: i)
		}else{
			typeAry.append(type)
		}
		
		typeString = typeAry.joined()
	}
	
	func textFieldShouldReturn(_ textField: UITextField) -> Bool {
		textField.resignFirstResponder()
		return true
	}
	
	@IBAction func cancel(_ sender: Any) {
		
		//let containsVC = parent?.parent as! ContainerViewController
        let containsVC = containerVC!
		containsVC.switchContentVC(to: 0)
		containsVC.setToPercent(0)
		
		if enterByPush{
			_ = navigationController?.popToRootViewController(animated: true)
		}else{
			dismiss(animated: true, completion: nil)
		}
	}
	
	// MARK: ViewController
	
	func initKsTypeSeg(){
		
		var idx = 0
		KsMain.type.allTypes.forEach {type in
			if type != .longTerm{
				ksTypeSeg.setTitle(type.rawValue.1, forSegmentAt: idx)
				idx += 1
			}
		}
		ksTypeSeg.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.white], for: .selected)
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		initKsTypeSeg()
		
		txtRange.delegate = self
		
		menuButton.isHidden = !enterByPush
		rangeLabel.adjustsFontSizeToFitWidth = true
	}

}
